<template>
  <view class="report-overview">
    <public-header title="报表概览"></public-header>
    <view class="real-time gap">
      <view class="real-time-title">
        实时数据
      </view>
      <view class="real-time-data">
        <view class="real-time-data-item gap" v-for="item in allCounts">
          <view class="icon">
            <image class="image" :src="item.icon" mode="aspectFill"></image>
            <!-- <img :src="item.icon" alt="" srcset=""> -->
          </view>
          <view class="text padding flex-column center">
            <view class="text-blod" style="font-weight: 600;">
              {{item.name}}
              <field-explain v-if="item.helpText" :text="item.helpText" position="center"></field-explain>
            </view>
            <view class>
              今日：<text v-if="item.prefix">{{item.prefix}}</text> {{item.today}}
              <uni-icons v-if="item.today > item.yesterday" custom-prefix="iconfont" color="#38C09E" type="arrow-up"
                size="20"></uni-icons>
              <uni-icons v-if="item.yesterday > item.today" custom-prefix="iconfont" color="#ff4747" type="arrow-down"
                size="20"></uni-icons>
              <!-- <span v-if="item.yesterday == item.today" style="color:#ff4747;font-size:20px;line-height: 20px;">=</span> -->
            </view>
            <view class="">
              昨日：<text v-if="item.prefix">{{item.prefix}}</text> {{item.yesterday}}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="manage-overview gap">
      <view class="manage-overview-title">
        经营总览
      </view>
      <view class="manage-overview-box">
        <view class="manage-overview-item gap" v-for="item in managementTotal">
          <view class="label">
            {{item.name}}
            <field-explain v-if="item.helpText" :text="item.helpText" position="center"></field-explain>
          </view>
          <view class="text">
            <text>{{item.total}}</text>{{item.unit}}
          </view>
        </view>
      </view>
    </view>
    <!--    <view class="report-overview-bottom gap">
      <date-range-selector ref="dateRangeFilter" :cfg="{}" @change="changeDateRange">
      </date-range-selector>
    </view> -->
    <view class="report-overview-bottom gap">
      <view class="flex full-width justify-end padding-bottom align-center" style="width: 100%;">
        <!-- <div class="tabs">
		  	<div class="tabs-day" id="tabs-day-id">日</div>
		  	<div class="tabs-week" id="tabs-week-id">周</div>
		  	<div class="tabs-month" id="tabs-month-id">月</div>
		  </div> -->
        <text>时间：</text>
        <view
          style="height: 4.5rem;margin-right: 2rem;max-width: 40rem;width: 40rem;line-height:4.5rem;padding: 0 10rpx; border: 1px solid #eeeeee;border-radius: 10rpx;display: flex;justify-content: space-between;background-color: #f2f2f2;"
          @click="checkDate">{{dateStringValueRun}}
          <!-- <u-icon name="calendar" ></u-icon> -->
          <uni-icons type="calendar" size="30"
            style="color: #38C09E;font-size:3rem;line-height: 4.2rem;position: relative;right: 10rpx;"></uni-icons>
        </view>
        <!-- <u--input
		 	    placeholder="请选择日期"
		 	    suffixIcon="calendar"
				
				v-model="dateStringRun"
		 	    suffixIconStyle="color: #00aa7f;font-size:3rem;"
				@focus="checkDate"
		 	></u--input> -->
        <uni-data-checkbox selectedColor="#38C09E" v-model="activeDateType" :localdata="dateType"></uni-data-checkbox>
        <u-datetime-picker ref="datetimePicker" confirmColor="#38C09E" v-if="activeDateType == 'year-month'"
          :show="showDatePicker" :value="datePickerTime" :mode="activeDateType == 'year-month' ? 'year-month' : 'date'"
          :formatter="formatter" @cancel="showDatePicker = false" @confirm="confirm"></u-datetime-picker>
        <!-- <picker mode="week" :value="datePickerTime" start="09:01" end="21:01" @change="confirm">
				<view class="uni-input">{{datePickerTime}}</view>
			</picker> -->
        <uni-calendar v-show="activeDateType == 'week' || activeDateType == 'day'" ref="calendar" :insert="false"
          :title="activeDateType == 'week' ?'周模式统计选择日期所在一周的结果':activeDateType == 'day' ?'日模式统计选择日期当天的结果':''"
          :showMonth="true" :range="dateRange" @change="change" @on-change="onChange" @confirm="confirm" />
      </view>
      <view class="flex full-width">
        <view class="bottom-item gap first-child">
          <view class="bottom-subtitle">
            交易趋势图
          </view>
          <view class="bottom-chart">
            <view class="bottom-chart-box">
              <l-echart ref="chart"></l-echart>
            </view>
            <view class="bottom-chart-right">
              <view class="bottom-chart-right-item">
                <view class="label">
                  应收合计(元)：
                </view>
                <view class="value">
                  {{dataLayout.total_receivable_amount}}
                </view>
              </view>
              <view class="bottom-chart-right-item">
                <view class="label">
                  实收合计(元)：
                </view>
                <view class="value">
                  {{dataLayout.total_pay_amount}}
                </view>
              </view>
              <view class="bottom-chart-right-item">
                <view class="label">
                  优惠合计(元)：
                </view>
                <view class="value">
                  {{dataLayout.total_dis_amount}}
                </view>
              </view>
              <view class="bottom-chart-right-item">
                <view class="label">
                  退单合计(元)：
                </view>
                <view class="value">
                  {{dataLayout.total_refund}}
                </view>
              </view>
              <view class="bottom-chart-right-item">
                <view class="label">
                  总单数（笔）：
                </view>
                <view class="value">
                  {{dataLayout.total_order_num}}
                </view>
              </view>
              <view class="bottom-chart-right-item">
                <view class="label">
                  平均消费(元)：
                </view>
                <view class="value">
                  {{dataLayout.avg_amount}}
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="bottom-item  flex-1 gap">
          <view class="bottom-subtitle">
            畅销商品排名
          </view>
          <view class="bottom-chart">
            <uni-table emptyText="暂无畅销商品">
              <uni-tr class="bg-gray">
                <uni-th style="width: 8rem;text-align: center;">排行</uni-th>
                <uni-th>商品名称</uni-th>
                <uni-th>销量</uni-th>
                <uni-th>销售额(￥)</uni-th>
              </uni-tr>
              <uni-tr v-for="(item,index) in goodsHotList" :key="index" v-if="index < 5">
                <uni-td style="text-align: center;">
                  <uni-badge class="uni-badge-left-margin" :text="index+1" type="primary"
                    :customStyle="{background: '#000000'}" />
                </uni-td>
                <uni-td>{{item.goods_name.length > 12 ? item.goods_name.slice(0,11) + '...' : item.goods_name}}</uni-td>
                <uni-td>{{item.goods_num}}</uni-td>
                <uni-td>{{item.ctual_amount}}</uni-td>
              </uni-tr>
            </uni-table>

          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  // 静态图片
  const maoli = require('@/static/icons/maoli.png');
  const shishou = require('@/static/icons/shishou.png');
  const bishu = require('@/static/icons/bishu.png');
  const xiashou = require('@/static/icons/xiashou.png');

  // 按需引入
  import * as echarts from 'echarts/core';
  import {
    LineChart,
  } from 'echarts/charts';
  import {
    TooltipComponent,
    TitleComponent,
    GridComponent,
    LegendComponent
  } from 'echarts/components';
  // 引入 Canvas 渲染器，注意引入 CanvasRenderer 是必须的一步
  import {
    CanvasRenderer
  } from 'echarts/renderers';

  // 注册必须的组件
  echarts.use([
    GridComponent,
    LegendComponent,
    TooltipComponent,
    TitleComponent,
    LineChart,
    CanvasRenderer
  ]);

  // srvretail_aio_home_select 实时数据
  // srvretail_aio_management_total_select 经营总览
  // srvretail_today_statistics_select 交易趋势图右边统计数据（日报）
  // srvretail_today_statistics_hour_select 交易趋势图（日报）
  // srvretail_thisweek_statistics_select 交易趋势图右边统计数据（周报）
  // srvretail_thisweek_statistics_day_select交易趋势图（周报）
  // srvretail_thismonth_statistics_select交易趋势图右边统计数据（月报）
  // srvretail_thismonth_statistics_day_select交易趋势图（月报）
  import dateRangeSelector from '@/components/custom-filter/comp/date-range-selector.vue'
  export default {
    components: {
      dateRangeSelector
    },
    data() {
      return {
        showDatePicker: false,
        datePickerTime: new Date().toLocaleDateString(),
        activeDateType: "day",
        dateRange: false,
        selected: [{
          date: '2022-12-29',
          info: '签到'
        }, {
          date: '2022-12-30',
          info: '签到'
        }],
        dataLayout: {
          avg_amount: 0,
          total_dis_amount: 0,
          total_order_num: 0,
          total_pay_amount: 0,
          total_receivable_amount: 0,
          total_refund: 0
        },
        dateType: [{
          text: "日",
          value: "day"
        }, {
          text: "周",
          value: "week"
        }, {
          text: "月",
          value: "year-month"
        }],

        // const maoli = require('@/static/icons/maoli.png');
        // const shishou = require('@/static/icons/shishou.png');
        // const bishu = require('@/static/icons/bishu.png');
        // const xiashou = require('@/static/icons/xiashou.png');

        allCounts: [{
          prefix: "￥",
          name: "实收总额",
          icon: '/static/icons/maoli.png',
          yesterday: "23222",
          today: "22222",
          helpText: "周期内，营业额为实际收到的金额，不包括会员卡消费，实收总额=会员充值-会员调额+现金收入+支付宝账户+微信账户+其他收入"
        }, {
          prefix: "￥",
          name: "销售总额",
          icon: '/static/icons/shishou.png',
          yesterday: "23222",
          today: "22222",
          helpText: "周期内，销售总额为商品实际销售的金额，不包括会员卡的充值，当售后退款时，需减少退款的销售额；销售总额=会员卡消费+现金收入+支付宝账户+微信账户+其他收入。"
        }, {
          name: "销售笔数",
          icon: '/static/icons/bishu.png',
          yesterday: "23222",
          today: "22222",
          helpText: "周期内，所有销售支付订单的总笔数，当订单售后部分退款时，销售笔数不减少，当订单售后全部退款成功时，销售笔数减少1"
        }, {
          name: "毛利",
          prefix: "￥",
          icon: '/static/icons/xiashou.png',
          yesterday: "23222",
          today: "22222",
          helpText: "周期内，毛利=销售总额-成本金额"
        }],
        managementTotal: [{
          name: "商品款数",
          total: 0,
          helpText: "累计平台所有的商品总款数",
          unit: "款"
        }, {
          name: "会员总数",
          total: 0,
          helpText: "累计平台所有的会员数量",
          unit: "人"
        }, {
          name: "可用储值",
          total: 0,
          helpText: "平台现所有会员的可用储值之和",
          unit: "元"
        }],
        goodsHotList: [],
        loaded: false,
        ranges: []

      }
    },
    computed: {
      dateStringRun: function() {
        let self = this
        let time = this.datePickerTime
        let type = this.activeDateType
        let str = ''
        // time = time ? new Date(time).toLocaleDateString() : new Date().toLocaleDateString()
        switch (type) {
          case 'day':
            // str = time
            str = this.dayjs(time).format("YYYY-MM-DD")
            break;
          case 'week':
            // str = time
            str = this.dayjs(time).format("YYYY-MM-DD")
            break;
          case 'year-month':
            // let nowM = (new Date(time).getMonth() + 1) > 12 ? '01' : (new Date(time).getMonth() + 1)
            // let nowY = new Date(time).getFullYear()
            // str = `${nowY}-${nowM}`
            str = this.dayjs(time).format("YYYY-MM")
            break;
          default:
            break;
        }
        return str
      },
      dateStringValueRun: function() {
        let self = this
        let time = ''
        if (typeof this.datePickerTime === 'string') {
          time = this.datePickerTime.replace(/\//g, "-")
        }
        let type = this.activeDateType
        let str = ''
        time = time || null
        time = this.dayjs(time).format("YYYY-MM-DD")
        // time = time ? new Date(time).toLocaleDateString() : new Date().toLocaleDateString()
        switch (type) {
          case 'day':
            // str = time.replace(/\//g, "-")
            str = this.dayjs(time).format("YYYY-MM-DD")
            break;
          case 'week':
            str = "" + this.dayjs(self.ranges[0]).format("YYYY-MM-DD") + '至' + this.dayjs(self.ranges[1]).format(
              "YYYY-MM-DD")
            // str = "" + self.ranges[0] + '至' + self.ranges[1]
            break;
          case 'year-month':
            // let nowM = (new Date(time).getMonth() + 1) > 12 ? '01' : (new Date(time).getMonth() + 1)
            // let nowY = new Date(time).getFullYear()
            // str = `${nowY}-${nowM}`
            str = this.dayjs(time).format("YYYY-MM")
            break;
          default:
            break;
        }
        return str
      }
    },
    mounted() {
      // this.initChart()
      this.getTotal()
      this.getAioHome()
      // this.loadChartData(this.dateStringRun,this.activeDateType)
      this.loadStatistics()
      this.loadChartData(this.dateStringRun, this.activeDateType)
      setTimeout(() => {
        this.getGoodsHot()
      }, 50)

    },
    onReady() {
      // 微信小程序需要用此写法
      // this.$refs.datetimePicker.setFormatter(this.formatter)
    },
    methods: {
      change(e) {
        console.log('@change', e)
      },
      onChange(e) {
        let type = this.activeDateType
        switch (type) {
          case 'day':
            this.selected = []
            break;
          case 'week':
            this.selected = []
            break;
          case 'month':
            this.selected = []
            break;
          default:
            this.selected = []
            break;
        }
        console.log('@onChange', e)
      },
      confirm(e) {
        let dateStr = this.dayjs().format("YYYY-MM-DD")
        let type = this.activeDateType
        switch (type) {
          case 'day':
            dateStr = e.fulldate
            break;
          case 'week':
            dateStr = e.fulldate
            break;
          case 'year-month':
            dateStr = this.dayjs(e.value).format("YYYY-MM-DD")
            // dateStr = new Date(e.value).toLocaleDateString()
            break;
          default:
            this.showDatePicker = true
            break;
        }
        this.datePickerTime = dateStr
        this.showDatePicker = false
        console.log('confirm', e, this.datePickerTime, type)
        // this.getDatas()
      },
      checkDate(e) {
        console.log(e)
        let type = this.activeDateType
        switch (type) {
          case 'day':
            this.$refs.calendar.open();
            break;
          case 'week':
            this.$refs.calendar.open();
            break;
          default:
            this.showDatePicker = true
            break;
        }
      },
      formatter(type, value) {
        if (type === 'year') {
          return `${value}年`
        }
        if (type === 'month') {
          return `${value}月`
        }
        if (type === 'day') {
          return `${value}日`
        }
        return value
      },
      groupChange(n) {
        console.log('groupChange', n);
      },
      radioChange(n) {
        console.log('radioChange', n);
      },
      changeDateRange(e) {
        console.log(e);
      },
      toDateStrList(date, daysNum) {
        let day = new Date(date).getTime()
        let dateStrList = []
        for (let i = 0; i < daysNum; i++) {
          let onDay = (new Date(day + (i * 1000 * 60 * 60 * 24)).getMonth() + 1) + '-' + (new Date(day + (i * 1000 *
            60 * 60 * 24)).getDate() < 10 ? '0' + new Date(day + (i * 1000 * 60 * 60 * 24)).getDate() : new Date(
            day + (i * 1000 * 60 * 60 * 24)).getDate())
          dateStrList.push(onDay)
        }
        return dateStrList

      },
      loadChartData(time, type) {
        // srvretail_today_statistics_hour_select 交易趋势图（日报）
        // srvretail_thisweek_statistics_day_select交易趋势图（周报）
        // srvretail_thismonth_statistics_day_select交易趋势图（月报）
        // 折线图数据
        let serviceName = ''
        let self = this
        time = time || this.dateStringRun
        let dateTypeReq = type || this.activeDateType
        let inputDate = this.dateStringRun
        let xLabel = []
        console.log('loadChartData', dateTypeReq)
        switch (dateTypeReq) {
          case 'day':
            serviceName = 'srvretail_today_statistics_hour_select'
            xLabel = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
            this.ranges = []
            this.ranges.push(`${time} 00:00:00`)
            this.ranges.push(`${time} 23:59:59`)
            break;
          case 'week':
            serviceName = 'srvretail_thisweek_statistics_day_select'
            let day = new Date(inputDate).getDay() == 0 ? 6 : new Date(inputDate).getDay() - 1;
            let stateY = new Date(inputDate).getFullYear();
            let endY = new Date(new Date(inputDate + ' 00:00:00').getTime() + (1000 * 60 * 60 * 24 * 7)).getFullYear();
            console.log('date', new Date(new Date(inputDate).getTime() - (day * 1000 * 60 * 60 * 24))
              .toLocaleDateString())
            xLabel = this.toDateStrList(new Date(new Date(inputDate).getTime() - (day * 1000 * 60 * 60 * 24))
              .toLocaleDateString(), 7)
            this.ranges = []
            this.ranges.push(`${''+stateY}-${xLabel[0]}`)
            this.ranges.push(`${''+endY}-${xLabel[xLabel.length - 1]}`)

            // console.log(xLabel,new Date(new Date(inputDate).getTime() - (day * 1000 * 60 * 60 * 24)).toLocaleDateString(),day)
            break;
          case 'year-month':
            time = time + '-01'
            serviceName = 'srvretail_thismonth_statistics_day_select'
            let nextM = (new Date(inputDate).getMonth() + 2) > 12 ? '01' : (new Date(inputDate).getMonth() + 2)
            let nextY = (nextM == '01') ? (new Date(inputDate).getFullYear() + 1) : new Date(inputDate).getFullYear()
            let nowM = (new Date(inputDate).getMonth() + 1) > 12 ? '01' : (new Date(inputDate).getMonth() + 1)
            let nowY = new Date(inputDate).getFullYear()
            let num = (new Date('' + nextY + '-' + nextM).getTime() - new Date('' + nowY + '-' + nowM).getTime()) / (
              1000 * 60 * 60 * 24)
            xLabel = this.toDateStrList('' + nowY + '-' + nowM + '-01', num)
            // console.log('---->',xLabel,''+nowY +'-'+nowM,''+nextY +'-'+nextM)
            this.ranges = []
            this.ranges.push(`${nowY}-${xLabel[0]}`)
            this.ranges.push(`${nowY}-${xLabel[xLabel.length - 1]}`)
            // this.ranges.push(xLabel[0]) 
            // this.ranges.push(xLabel[xLabel.length - 1]) 
            break;
        }
        var x = [];
        var y = [];
        var z = [];
        var option = {};
        var bxReq = {};
        bxReq.serviceName = serviceName;
        bxReq.colNames = ["*"];
        bxReq.condition = [{
          "colName": "day_time",
          "value": time,
          "ruleType": "eq"
        }];
        bxReq.relation_condition = {};
        bxReq.page = {
          "pageNo": 1,
          "rownumber": 100
        }
        bxReq.order = [];
        x = xLabel
        self.$fetch('select', serviceName, bxReq).then((res) => {
          if (res.success) {
            console.log(res.data)
            let resData = res.data
            switch (serviceName) {
              case 'srvretail_today_statistics_hour_select':
                resData.sort((a, b) => a.hour_time - b.hour_time)
                for (let j = 0; j < x.length; j++) {
                  y[j] = 0
                  z[j] = 0
                  for (let index = 0; index < resData.length; index++) {
                    const element = resData[index];
                    if (element.hour_time == x[j]) {

                      y[j] = element.total_pay_amount
                      z[j] = element.total_receivable_amount
                    }
                  }

                }
                break;
              case 'srvretail_thisweek_statistics_day_select':
                for (let j = 0; j < x.length; j++) {

                  y[j] = 0
                  z[j] = 0
                  for (let index = 0; index < resData.length; index++) {
                    const element = resData[index];
                    // console.log(element.hour_time,x[j])
                    if (element.date_time.indexOf(x[j]) > -1) {
                      y[j] = element.total_pay_amount
                      z[j] = element.total_receivable_amount
                    }
                    // if (element.date_time == x[j]) {

                    //   y[j] = element.total_pay_amount
                    //   z[j] = element.total_receivable_amount
                    // }
                  }
                }
                break;
              case 'srvretail_thismonth_statistics_day_select':
                for (let j = 0; j < x.length; j++) {
                  y[j] = 0
                  z[j] = 0
                  for (let index = 0; index < resData.length; index++) {
                    const element = resData[index];
                    // console.log(element.date_time,x[j])
                    if (element.date_time.indexOf(x[j]) > -1) {
                      y[j] = element.total_pay_amount
                      z[j] = element.total_receivable_amount
                    }
                    // if (element.date_time == x[j]) {
                    //   y[j] = element.total_pay_amount
                    //   z[j] = element.total_receivable_amount
                    // }
                  }

                }
                break;
              default:
                break;
            }
            if (resData.length == 0) { //暂无数据
              this.setChartsOption(x, y, z, dateTypeReq)
            } else {
              this.setChartsOption(x, y, z, dateTypeReq)
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        })
      },
      setChartsOption(xData, seriesData, seriesData2, type) {
        const hexToRgba = (hex, opacity) => {
          let rgbaColor = "";
          let reg = /^#[\da-f]{6}$/i;
          if (reg.test(hex)) {
            rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
              "0x" + hex.slice(3, 5)
            )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
          }
          return rgbaColor;
        }
        let emptyX = []
        switch (type) {
          case 'day':
            emptyX = ['01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00',
              '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00',
              '19:00', '20:00', '21:00', '22:00', '23:00', '24:00'
            ]
            break;
          case 'week':
            emptyX = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
            break;
          case 'month':
            emptyX = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
            break;

        }
        let option = {
          color: ['#38C09E', '#4969F5', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622',
            '#bda29a', '#6e7074', '#546570', '#c4ccd3'
          ],
          title: {
            text: ''
          },
          grid: {
            left: '15%',
            right: "15%",
            top: "20%",
            bottom: "10%"
          },
          legend: {
            show: true,
            // data: ['应收合计', '实收合计'],
            data: [{
              name: '应收合计',
              // icon: 'line',
              // textStyle: {
              //   color: '#11a4ff'
              // },
            }, {
              name: '实收合计',
              // icon: 'line',
              // textStyle: {
              //   color: '#ff0000'
              // },
            }]
          },
          xAxis: {
            name: '时间',
            nameTextStyle: {
              color: '#333'
            },
            axisLabel: {
              color: "#333"

            },
            axisLine: {
              lineStyle: {
                color: "#e7e7e7"
              }
            },
            data: xData || emptyX
          },
          yAxis: {
            axisLabel: {
              color: "#333"

            },
            nameTextStyle: {
              color: '#333'
            },
            axisLine: {
              lineStyle: {
                color: "#e7e7e7"
              }
            },
            name: '(元)',
          },
          series: [{
            name: '应收合计',
            type: 'line',
            // lineStyle: {
            //   normal: {
            //     color: '#38C09E',
            //     shadowBlur: 3,
            //     shadowColor: hexToRgba('#38C09E', 0.5),
            //     shadowOffsetY: 8
            //   }
            // },
            areaStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [{
                      offset: 0,
                      color: hexToRgba('#38C09E', 0.3)
                    },
                    {
                      offset: 1,
                      color: hexToRgba('#38C09E', 0.1)
                    }
                  ],
                  false
                ),
                shadowColor: hexToRgba('#38C09E', 0.1),
                shadowBlur: 10
              }
            },
            data: seriesData2 || []
          }, {
            name: '实收合计',
            type: 'line',
            // lineStyle: {
            //   normal: {
            //     color: '#4969F5',
            //     shadowBlur: 3,
            //     shadowColor: hexToRgba('#4969F5', 0.5),
            //     shadowOffsetY: 8
            //   }
            // },
            areaStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [{
                      offset: 0,
                      color: hexToRgba('#4969F5', 0.3)
                    },
                    {
                      offset: 1,
                      color: hexToRgba('#4969F5', 0.1)
                    }
                  ],
                  false
                ),
                shadowColor: hexToRgba('#4969F5', 0.1),
                shadowBlur: 10
              }
            },
            data: seriesData || []
          }],
          tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
            trigger: 'axis',
            backgroundColor: 'rgba(32, 33, 36,.7)',
            borderColor: 'rgba(32, 33, 36,0.20)',
            borderWidth: 1,
            textStyle: { // 文字提示样式
              color: '#fff',
              fontSize: '12'
            },
            axisPointer: { // 坐标轴虚线
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            },
          }
        };
        this.$refs.chart.init(echarts, chart => {
          chart.setOption(option);
        });

      },
      loadStatistics(time) {
        // 趋势图右侧统计
        let self = this
        let serviceName = ''
        let dateType = this.activeDateType
        // time = time || getToDay()
        let date = this.dateStringRun

        // srvretail_today_statistics_select 交易趋势图右边统计数据（日报）
        // srvretail_thisweek_statistics_select 交易趋势图右边统计数据（周报）
        // srvretail_thismonth_statistics_select交易趋势图右边统计数据（月报）
        switch (dateType) {
          case 'day':
            serviceName = 'srvretail_today_statistics_select'
            break;
          case 'week':
            serviceName = 'srvretail_thisweek_statistics_select'
            break;
          case 'year-month':
            date = date + '-01'
            serviceName = 'srvretail_thismonth_statistics_select'
            break;
        }
        let bxReq = {};
        bxReq.serviceName = serviceName;
        bxReq.colNames = ["*"];
        bxReq.condition = [{
          "colName": "day_time",
          "value": date,
          "ruleType": "eq"
        }];
        bxReq.page = {
          "pageNo": 1,
          "rownumber": 100
        }
        self.$fetch('select', serviceName, bxReq).then((res) => {
          if (res.success) {
            console.log('loadStatistics', res.data)
            let data = res.data[0]
            if (data) {
              this.$set(this, 'dataLayout', data)
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        })


      },

      getAioHome() {
        let self = this
        let req = {
          "serviceName": 'srvretail_aio_home_select',
          "condition": []
        }
        self.$fetch('select', 'srvretail_aio_home_select', req).then((res) => {
          if (res.success) {
            let data = res.data[0]
            for (let item of this.allCounts) {
              switch (item.name) {
                case '实收总额':
                  item.today = data['today_real_income_amount']
                  item.yesterday = data['yesterday_real_income_amount']
                  break;
                case '销售总额':
                  item.today = data['today_turnover']
                  item.yesterday = data['yesterday_turnover']
                  break;
                case '销售笔数':
                  item.today = data['today_order_num']
                  item.yesterday = data['yesterday_order_num']
                  break;
                case '毛利':
                  item.today = data['today_profit']
                  item.yesterday = data['yesterday_profit']
                  break;
                default:
                  break;
              }
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        })
      },
      getTotal() {
        let self = this
        let req = {
          "serviceName": 'srvretail_aio_management_total_select',
          "condition": []
        }
        self.$fetch('select', 'srvretail_aio_management_total_select', req).then((res) => {
          if (res.success) {
            let data = res.data[0]
            for (let item of this.managementTotal) {
              switch (item.name) {
                case '商品款数':
                  item.total = data['all_goods']
                  break;
                case '会员总数':
                  item.total = data['member_total']
                  break;
                case '可用储值':
                  item.total = data['balance_total']
                  break;
                default:
                  break;
              }
            }
          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        })
      },
      getGoodsHot(e) {
        let self = this
        let req = {
          "serviceName": 'srvretail_product_reaport_info_select',
          "condition": [],
          "relation_condition": {
            "relation": "AND",
            "data": [{
              "relation": "OR",
              "data": [{
                "colName": "create_time",
                "ruleType": "between",
                "value": this.ranges
              }]
            }, {
              "colName": "goods_num",
              "ruleType": "ne",
              "value": 0
            }]
          }
        }
        self.$fetch('select', 'srvretail_product_reaport_info_select', req).then((res) => {
          if (res.success) {
            let data = res.data
            this.goodsHotList = data.map(item => item)

          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        })

      },
      initChart() {
        let option = {
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            data: ['应收合计', '实收合计']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
              name: '应收合计',
              type: 'line',
              stack: '总量',
              data: [120, 132, 101, 134, 90, 230, 210]
            },
            {
              name: '实收合计',
              type: 'line',
              stack: '总量',
              data: [220, 182, 191, 234, 290, 330, 310]
            },
          ]
        }

        this.$refs.chart.init(echarts, chart => {
          chart.setOption(option);
        });
      },
    },
    watch: {
      'activeDateType': {
        deep: true,
        handler: function(newValue, oldValue) {
          let self = this
          console.log('activeDateType', newValue)
          switch (newValue) {
            case 'week':
              self.dateRange = true
              break;
            default:
              self.dateRange = false
              break;
          }
          this.loadStatistics()
          this.loadChartData(this.dateStringRun, this.activeDateType)
          this.getGoodsHot()
        }
      },
      'datePickerTime': {
        deep: true,
        handler: function(newValue, oldValue) {
          this.loadStatistics()
          this.loadChartData(this.dateStringRun, this.activeDateType)
          this.getGoodsHot()
        }
      }
      // datePickerTime: new Date().toLocaleDateString(),
      // activeDateType:"day",
    },
  }
</script>

<style lang="scss" scoped>
  .report-overview {
    font-size: 2.4rem;
    padding: 2rem;

    .gap {
      padding: 2rem;
      border-radius: 1rem;
      background-color: #fff;
    }

    // .real-time-data-item{
    // 	display: flex;
    // }
    .real-time {
      margin-bottom: 2rem;

      &-title {
        font-weight: bold;
        margin-bottom: 1rem;
      }

      &-data {
        display: flex;

        &-item {
          flex: 1;
          display: flex;
          margin-right: 2rem;
          border: 1px solid #e5e5e5;
          flex-direction: row;

          & .icon {
            display: flex;
            align-items: center;

            .image {
              width: 10rem;
              height: 10rem;
            }
          }

          & .text {
            padding-left: 20rpx;
            display: flex;
            flex-direction: column;
            // align-items: center;
            justify-content: center;

            &:first-child {
              font-weight: 800;
              display: flex;

              .field-explain {
                height: 40rpx;
              }
            }
          }

          &:last-child {
            margin-right: 0;
          }
        }
      }
    }

    .manage-overview {
      margin-bottom: 2rem;

      &-title {
        font-weight: bold;
        margin-bottom: 1rem;
      }

      &-box {
        display: flex;
      }

      &-item {
        display: flex;
        flex: 1;
        margin-right: 2rem;
        border-right: 1px solid #f5f5f5;
        border-radius: 10rpx;
        text-align: center;
        background-color: #f5f5f5;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding: 10rpx 40rpx;

        &:last-child {
          border: none;
        }

        .label {
          font-size: 2.8rem;
          // margin-top: 1rem;
        }

        .text {
          font-size: 2.8rem;
          color: $retail-color-primary;
          font-weight: 800;
        }
      }
    }

    &-bottom {
      display: flex;
      flex-wrap: wrap;

      .bottom-item {
        border: 1px solid #e3e3e3;

        &.first-child {
          margin-right: 2rem;
          width: 60vw;
        }

        ::v-deep .uni-table {
          min-width: 0 !important;
        }
      }

      .bottom-subtitle {
        font-weight: bold;
        margin-bottom: 1rem;
      }

      .bottom-chart {
        display: flex;
        width: 100%;

        &-box {
          // flex: 1;
          width: calc(100% - 35rem);
          height: 100%;
          padding: 1rem;
          border: 1px solid #e5e5e5;
          margin-right: 2rem;

        }

        &-right {
          width: 35rem;
          display: flex;
          padding: 20rpx;
          flex-direction: column;
          justify-content: center;
          background-color: #f5f5f5;
          border-radius: 10rpx;

          &-item {
            display: flex;
            justify-content: space-between;
            padding: 1rem 0;
          }
        }
      }
    }
  }
</style>
